package my.springboot.validation.verify.impl;

import java.io.UnsupportedEncodingException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.vdurmont.emoji.EmojiParser;

import my.springboot.validation.verify.CharCheck;
import my.springboot.validation.verify.CharCheck.CharEnum;

public class CharCheckImpl implements ConstraintValidator<CharCheck, String>{

	private CharEnum[] value;
	
	@Override
	public void initialize(CharCheck constraintAnnotation) {
		this.value = constraintAnnotation.value();
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		String regex = "^[";
		boolean hasRegex = false;
		boolean isUtf8 = true;
		boolean exceptEmoji = true;
		for (CharEnum charEnum : this.value) {
			if(CharEnum.utf8.equals(charEnum)){
				isUtf8 = chechUtf8(value);
			}else if(CharEnum.english.equals(charEnum)){
				regex += "a-zA-Z";
				hasRegex = true;
			}else if(CharEnum.chinese.equals(charEnum)){
				regex += "\u4e00-\u9fa5";
				hasRegex = true;
			}else if(CharEnum.number.equals(charEnum)){
				regex += "0-9";
				hasRegex = true;
			}else if(CharEnum.exceptEmoji.equals(charEnum)){
				exceptEmoji = checkEmoji(value);
			}
		}
		boolean matches = true;
		if(hasRegex){
			regex += "]*$";
			matches = value.matches(regex);
		}
		return isUtf8 && matches && exceptEmoji;
	}
	
	/**
	 * 检测是否是utf-8的字符
	 * @param value
	 * @return
	 */
	private boolean chechUtf8(String value){
		String encoding = "UTF-8";  
        try {
            if (value.equals(new String(value.getBytes(),encoding))) {  
                return true;  
            }
        } catch (UnsupportedEncodingException e) {  
            return false;  
        }  
		return false;
	}
	
	/**
	 * 检测是否是表情
	 * @param value
	 * @return
	 */
	private boolean checkEmoji(String value){
		if(value == null){
			return true;
		}
		String parseToAliases = EmojiParser.parseToAliases(value);
		if(value.equals(parseToAliases)){
			return true;
		}
		return false;
	}
	
}
